#!/usr/bin/env python
import coverage
import os
import pytest
import subprocess
import sys


PYTEST_ARGS = ['tests', '--tb=short']
FLAKE8_ARGS = ['coreapi', 'tests', '--ignore=E501', '--exclude', 'compat.py']
COVERAGE_OPTIONS = {
    'include': ['coreapi/*', 'tests/*'],
    'omit': ['coreapi/compat.py']
}


sys.path.append(os.path.dirname(__file__))


class NullFile(object):
    def write(self, data):
        pass


def exit_on_failure(ret, message=None):
    if ret:
        sys.exit(ret)


def flake8_main(args):
    print('Running flake8 code linting')
    ret = subprocess.call(['flake8'] + args)
    print('flake8 failed' if ret else 'flake8 passed')
    return ret


def report_coverage(cov, fail_if_not_100=False):
    percent_covered = cov.report(
        file=NullFile(), **COVERAGE_OPTIONS
    )
    if percent_covered == 100:
        print('100% coverage')
        return
    if fail_if_not_100:
        print('Tests passed, but not 100% coverage.')
    cov.report(**COVERAGE_OPTIONS)
    cov.html_report(**COVERAGE_OPTIONS)
    if fail_if_not_100:
        sys.exit(1)


def split_class_and_function(string):
    class_string, function_string = string.split('.', 1)
    return "%s and %s" % (class_string, function_string)


def is_function(string):
    # `True` if it looks like a test function is included in the string.
    return string.startswith('test_') or '.test_' in string


def is_class(string):
    # `True` if first character is uppercase - assume it's a class name.
    return string[0] == string[0].upper()


if __name__ == "__main__":
    if len(sys.argv) > 1:
        pytest_args = sys.argv[1:]
        first_arg = pytest_args[0]
        if first_arg.startswith('-'):
            # `runtests.py [flags]`
            pytest_args = PYTEST_ARGS + pytest_args
        elif is_class(first_arg) and is_function(first_arg):
            # `runtests.py TestCase.test_function [flags]`
            expression = split_class_and_function(first_arg)
            pytest_args = PYTEST_ARGS + ['-k', expression] + pytest_args[1:]
        elif is_class(first_arg) or is_function(first_arg):
            # `runtests.py TestCase [flags]`
            # `runtests.py test_function [flags]`
            pytest_args = PYTEST_ARGS + ['-k', pytest_args[0]] + pytest_args[1:]
    else:
        pytest_args = PYTEST_ARGS

    cov = coverage.coverage()
    cov.start()
    exit_on_failure(pytest.main(pytest_args))
    cov.stop()
    exit_on_failure(flake8_main(FLAKE8_ARGS))
    report_coverage(cov)
